/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.globussoft.xml;

/**
 *
 * @author Dj
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class XmlSchedulingStore {

    Document dom;
    private boolean auto_backup;
    private int cpu_work;
    private int idle_time;
    private int backup_times;
    private boolean scheduled;
    private String schedul_parameter;
    private String selectedDay;
    private int schedul_back_at;
    private int schedul_back_days = 1;
    private boolean tempSuspend;
    private boolean backNoNetwork;
    private boolean batteryRun;
    private String projectName = "Pomblast";
    private static XmlSchedulingStore xmlSchedulingObject=null;

    public static XmlSchedulingStore getnstance()
    {
        if(xmlSchedulingObject==null)
           xmlSchedulingObject=new XmlSchedulingStore();
        return xmlSchedulingObject;
    }
    private XmlSchedulingStore() {
        projectName = SettingsXml.getProjectName();
    }

    public boolean getAutomatic() {

        return auto_backup;

    }

    public void setAutomatic(boolean auto_backup) {

        this.auto_backup = auto_backup;
    }

    public int getCPU_WorkTime() {

        return cpu_work;

    }

    public void setCPU_WorkTime(int cpu_work) {

        this.cpu_work = cpu_work;

    }

    public int getIdle_Time() {

        return idle_time;

    }

    public void setIdle_Time(int idle_time) {

        this.idle_time = idle_time;

    }

    public int getBackUp_Times() {

        return backup_times;

    }

    public void setBackUp_Times(int backup_times) {

        this.backup_times = backup_times;
    }

    public boolean getSchedulued_BackUp() {

        return scheduled;

    }

    public void setSchedulued_BackUp(boolean scheduled) {

        this.scheduled = scheduled;

    }

    public String getScheduling_Parameter() {

        return schedul_parameter;

    }

    public void setScheduling_Parameter(String schedul_parameter) {

        this.schedul_parameter = schedul_parameter;

    }

    public String getSelectedDay() {

        return selectedDay;

    }

    public void setSelectedDay(String selectedDay) {

        this.selectedDay = selectedDay;

    }

    public boolean getTempSuspend() {
        return tempSuspend;
    }

    public void setTempSuspend(boolean tempSuspend) {
        this.tempSuspend = tempSuspend;
    }

    public boolean getBatteryRun() {
        return batteryRun;
    }

    public void setBatteryRun(boolean batteryRun) {
        this.batteryRun = batteryRun;
    }

    public boolean getNoNetBackup() {
        return backNoNetwork;
    }

    public void setNoNetBackup(boolean backNoNetwork) {
        this.backNoNetwork = backNoNetwork;
    }

    public int getScheduling_BackUp_At() {

        return schedul_back_at;

    }

    public void setScheduling_BackUp_At(int schedul_back_at) {

        this.schedul_back_at = schedul_back_at;

    }

    public int getScheduling_BackUp_Days() {

        return schedul_back_days;

    }

    public void setScheduling_BackUp_Days(int schedul_back_days) {

        this.schedul_back_days = schedul_back_days;

    }

    public void writeGeneralXml(String filename) throws ParserConfigurationException {

        //create a list to hold the data
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            dom = db.newDocument();

            Element rootElement = dom.createElement("General-Settings");

            // dom.appendChild(rootElement);

            Element generalElement = dom.createElement("Scheduling");

            generalElement = createGeneralElement(generalElement, "Automatic-Backup", "" + auto_backup);
            generalElement = createGeneralElement(generalElement, "CPU-Working", "" + cpu_work);
            generalElement = createGeneralElement(generalElement, "Idle-Time", "" + idle_time);
            generalElement = createGeneralElement(generalElement, "BackUp-Times", "" + backup_times);
            generalElement = createGeneralElement(generalElement, "Scheduled", "" + scheduled);
            generalElement = createGeneralElement(generalElement, "selectedDay", "" + selectedDay);
            generalElement = createGeneralElement(generalElement, "Scheduling-Parameter", "" + schedul_parameter);
            generalElement = createGeneralElement(generalElement, "Scheduled-BackUp-At", "" + schedul_back_at);
            generalElement = createGeneralElement(generalElement, "Scheduled-BackUp-Days", "" + schedul_back_days);
            rootElement.appendChild(generalElement);
            dom.appendChild(rootElement);

            try {
                printToFile(dom, filename);
            } catch (Exception ex) {
            }



        } catch (ParserConfigurationException pce) {

            //  System.out.println("Error while trying to instantiate DocumentBuilder " + pce);

            System.exit(1);

        }


    }

    /**
     * Helper method which creates a XML element
     * @param xmlgeneralstore The SetXmlGeneralStore for which we need to create an xml representation
     * @return XML element snippet representing a SetXmlGeneralStore
     */
    private Element createGeneralElement(Element generalElement, String property, String value) {


        //create Status element and Status text node and attach it to generalElement
        Element statusElement = dom.createElement(property);

        Text statusText = dom.createTextNode(value);

        statusElement.appendChild(statusText);

        generalElement.appendChild(statusElement);


        return generalElement;

    }

    private void printToFile(Document dom, String filename) throws FileNotFoundException, IOException {
        try {

            OutputFormat format = new OutputFormat(dom);
            format.setIndenting(true);
            //URL mySource = XmlGeneralStore.class.getProtectionDomain().getCodeSource().getLocation();
            //  File sourceFile = new File(".");
            boolean success;
            String source = System.getProperty("user.home");
            String dir = source + "\\" + projectName;
            File sourceFile = new File(dir);
            if (!sourceFile.exists()) {
                success = new File(dir).mkdir();
            }


            // attach text file to application directory(.class file)
            String xmlfile = dir + "\\" + filename;

            //to generate output to console use this serializer

            //XMLSerializer serializer = new XMLSerializer(System.out, format);

            //to generate a file output use fileoutputstream instead of system.out

            XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(xmlfile)), format);
            serializer.serialize(dom);

        } catch (IOException ie) {
            ie.printStackTrace();
        }

    }

    //reading the xml file code her
    public void ReadGeneralXml(String filename) {
        // String storegenerralxml[]=new String[10];
        try {
            // URL mySource = XmlGeneralStore.class.getProtectionDomain().getCodeSource().getLocation();
            // File sourceFile = new File(".");
            // attach text file to application directory(.class file)
            //String xmlfile = sourceFile.getAbsolutePath()+"\\"+"generalsettings.xml";
            boolean success;
            String source = System.getProperty("user.home");
            String dir = source + "\\" + projectName;
            File fXmlFile = new File(dir + "\\" + filename);
            if (fXmlFile.isFile()) {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);
                doc.getDocumentElement().normalize();

                // System.out.println("General Settings :" + doc.getDocumentElement().getNodeName());
                NodeList nList = doc.getElementsByTagName("Scheduling");
                //  System.out.println("-----------------------");

                for (int temp = 0; temp < nList.getLength(); temp++) {

                    Node nNode = nList.item(temp);

                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                        Element eElement = (Element) nNode;

//	     storegenerralxml[0]= getTagValue("Bandwidth",eElement);
//	     storegenerralxml[1]= getTagValue("Limit",eElement);
//	     storegenerralxml[2]=getTagValue("Throttle",eElement).trim();
                        String auto_backuptemp = getTagValue("Automatic-Backup", eElement).trim();
                        if (auto_backuptemp.equals("false")) {
                            auto_backup = false;
                        } else {
                            auto_backup = true;
                        }
                        String cpu_worktemp = getTagValue("CPU-Working", eElement);
                        cpu_work = Integer.parseInt(cpu_worktemp);
                        String idle_timetemp = getTagValue("Idle-Time", eElement);
                        idle_time = Integer.parseInt(idle_timetemp);
                        String backup_timestemp = getTagValue("BackUp-Times", eElement);
                        backup_times = Integer.parseInt(backup_timestemp);
                        String scheduledtemp = getTagValue("Scheduled", eElement).trim();
                        if (scheduledtemp.equals("false")) {
                            scheduled = false;
                        } else {
                            scheduled = true;
                        }

                        schedul_parameter = getTagValue("Scheduling-Parameter", eElement);
                        if (schedul_parameter.equals("Daily")) {
                            schedul_parameter = "Daily";
                        } else {
                            schedul_parameter = "Weekly";
                        }
                        selectedDay = getTagValue("selectedDay", eElement);
                        String schedul_back_attemp = getTagValue("Scheduled-BackUp-At", eElement);
                        schedul_back_at = Integer.parseInt(schedul_back_attemp);
                        String schedul_back_daystemp = getTagValue("Scheduled-BackUp-Days", eElement).trim();
                        schedul_back_days = Integer.parseInt(schedul_back_daystemp);

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //return storegenerralxml;
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        return nValue.getNodeValue();
    }

    public static String getStoredValue()
    {
     String storedValue="";
     XmlSchedulingStore xml =getnstance();
     xml.ReadGeneralXml("schedulingsettings.xml");
     storedValue=xml.getAutomatic()+" "+xml.getCPU_WorkTime()+" "+xml.getIdle_Time()+" "+xml.getBackUp_Times()+" "+xml.getSchedulued_BackUp()+" "+xml.getScheduling_Parameter()+" "+xml.getScheduling_BackUp_At()+" "+xml.getSelectedDay().trim()+" "+xml.getScheduling_BackUp_Days();
     return storedValue;
    }
    public static String getAutoStartTime() {
        String str = "";
        XmlSchedulingStore xml = getnstance();//new XmlSchedulingStore();
        xml.ReadGeneralXml("schedulingsettings.xml");
        if (!xml.getAutomatic())  {

            if (xml.getScheduling_Parameter().equals("Daily")) {
                str = "Daily " + xml.getScheduling_BackUp_At() + " " + xml.getScheduling_BackUp_Days();
            } else {
                str = "Weekly " + xml.getScheduling_BackUp_At() + " " + xml.getSelectedDay().trim() + " " + xml.getScheduling_BackUp_Days();
            }
        }
        return str;
    }

    public static void main(String[] arg) {
        //XmlSchedulingStore xml = new XmlSchedulingStore();
        System.out.println(getStoredValue());
//        xml.ReadGeneralXml("schedulingsettings.xml");
//        if (xml.getAutomatic()) {
//            System.out.println(xml.getCPU_WorkTime());
//            System.out.println(xml.getIdle_Time());
//            System.out.println(xml.getBackUp_Times());
//
//        } else {
//            String str = "";
//            if (xml.getScheduling_Parameter().equals("Daily")) {
//                str = "Daily " + xml.getScheduling_BackUp_At() + " " + xml.getScheduling_BackUp_Days();
//            } else {
//                str = "Weekly " + xml.getScheduling_BackUp_At() + " " + xml.getSelectedDay().trim() + " " + xml.getScheduling_BackUp_Days();
//            }
//            System.out.println(str);
//        }
    }
}
